package cn.edu.nuc.fourth.controller;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.edu.nuc.fourth.dto.PageInfo;
import cn.edu.nuc.fourth.model.Major;
import cn.edu.nuc.fourth.services.interfaces.FillingService;

@Controller
@RequestMapping("/major")
public class MajorController {

	@Autowired
	private FillingService service;

	@RequestMapping("/major")
	public String initMajor() {

		return "schooluser/majorAdd";
	}

	@RequestMapping(value = "/majoradd", method = RequestMethod.POST)
	public String addMajor(@Valid @ModelAttribute("major") Major major, Errors errors) {

		if (errors.hasErrors()) {
			System.out.println("校验专业填报");
			return "schooluser/majorAdd";
		}
		Integer result = service.majorAdd(major);
		return "OK";
	}

	@RequestMapping("/majorlist")
	public String majorList(Integer userid, @RequestParam(name = "current", defaultValue = "1") Integer current,
			Model model) {

		PageInfo pageInfo = service.majorList(-1, current);
		PageInfo pageSchool = service.schoolList(-1, 1);
		model.addAttribute("page", pageSchool);
		model.addAttribute("pagemajor", pageInfo);
		return "schooluser/school";
	}

	@RequestMapping(value = "/ajax", method = RequestMethod.POST)
	public @ResponseBody PageInfo ajaxList(Integer userid, Integer current) {

		PageInfo pageInfo = service.majorList(userid, current);
		return pageInfo;
	}

	@RequestMapping("/onemajor")
	public String oneMajor(Integer majorid, Model model) {

		Major major = service.oneMajor(majorid);
		model.addAttribute("major", major);

		if (major.getState() == 1) {

			return "schooluser/noeditMajor";
		}
		return "schooluser/oneMajor";
	}

	@RequestMapping(value = "/majoredit", method = RequestMethod.POST)
	public String editMajor(Major major, Model model) {

		Major m = service.majorEdit(major);
		model.addAttribute("major", m);
		return "schooluser/oneMajor";

	}
	@RequestMapping("/noedit")
	public String noedit(Integer majorid,Integer state,Model model){
		
		Major major=service.noeditMajor(majorid, state);
		model.addAttribute("major", major);
		return "schooluser/noeditMajor";
	}
	@RequestMapping("/majordelete")
	public String majordelete(Integer majorid){
		
		Integer result = service.deleteMajor(majorid);
		return "redirect:/school/schoollist";
	}
}
